package com.intramirror.product.service.impl;

import com.intramirror.product.entity.LimitTime;
import com.intramirror.product.entity.LimitTimeItem;
import com.intramirror.product.entity.TagProductRel;
import com.intramirror.product.mapper.LimitTimeItemMapper;
import com.intramirror.product.mapper.LimitTimeMapper;
import com.intramirror.product.mapper.TagProductRelMapper;
import com.intramirror.product.service.ILimitTimeService;
import com.intramirror.product.vo.LImitTimeVO;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
public class LimitTimeServiceImpl implements ILimitTimeService {

    private final static Logger LOGGER = LoggerFactory.getLogger(LimitTimeServiceImpl.class);

    @Autowired
    LimitTimeMapper limitTimeMapper;

    @Autowired
    LimitTimeItemMapper limitTimeItemMapper;

    @Autowired
    TagProductRelMapper tagProductRelMapper;

    private List<LimitTime> getLimitTime() {
        return limitTimeMapper.getLimitTime();
    }

    private List<LimitTimeItem> getLimitTimeItems(Long limitTimeId) {
        LimitTimeItem lti = new LimitTimeItem();
        lti.setLimitTimeId(limitTimeId);
        return limitTimeItemMapper.getLimitTimeItemByCond(lti);
    }

    @Override
    public LImitTimeVO getLimitTimeInfo() {
        LImitTimeVO ltVO = new LImitTimeVO();

        List<LimitTime> listLT = getLimitTime();
        if (listLT.size() != 1) {
            LOGGER.error("The config for limit_time contains not only one active record!");
            return null;
        }

        LimitTime lt = listLT.get(0);
        List<LimitTimeItem> listLTI = getLimitTimeItems(lt.getLimitTimeId());
        if (listLTI == null || listLTI.size() <= 0) {
            LOGGER.error("The config for limit_time_itme has no record!");
            return null;
        }

        ltVO.setLimitTime(lt);
        ltVO.setListLimitTimeItem(listLTI);
        return ltVO;
    }

    @Override
    public Boolean saveLimitTimeProducts(List<TagProductRel> listTagPrdRel, Long tagId) {
        tagProductRelMapper.deleteByTagId(tagId);
        for (TagProductRel tpl : listTagPrdRel) {
            tagProductRelMapper.insertSelective(tpl);
        }
        return true;
    }

    @Override
    public Boolean saveLimitTime(LimitTime lt) {
        limitTimeMapper.updateByPrimaryKeySelective(lt);
        return true;
    }

    @Override
    public void saveLimitItemDescription(Long tagId, String itemDescription) {
        LimitTimeItem limitTimeItem = new LimitTimeItem();
        limitTimeItem.setTagId(tagId);
        limitTimeItem.setItemDescription(itemDescription);
        limitTimeMapper.updateLimitItem(limitTimeItem);
    }

}
